package lastfm
{
  import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
  import flash.net.URLLoader;
  import flash.net.URLRequest;
  import lastfm.Api;
  import lastfm.events.ApiEvent;
  import lastfm.events.AutocompleterEvent;
  import lastfm.events.RequestEvent;
  import mx.collections.ArrayList;
  import mx.rpc.http.HTTPService;
  import mx.rpc.events.ResultEvent;
  import mx.rpc.events.FaultEvent;
  import PrivateVars.lastfm;
  import Tools.Debug;
  import vk.api.serialization.json.JSON;
	
	/**
   * ...
   * @author Roman Marchenko
   */
  public class Autocompleter extends EventDispatcher
  {
    public static const TYPE_ARTIST : uint = 6;
    public static const TYPE_TAG:uint = 32;
    public var _currentSearchStr: String;

    private var types:Array;

    public function Autocompleter(... args)
    {
      super(null);
      types = new Array;
      for (var i:uint = 0; i < args.length; i++)
      {
        if (!(args[i] is uint))
        {
          throw "Wrong argument type, expecting uint.";
    }

        types.push(args[i] as uint);
      }
    }

    public function search (str: String): void
    {
      Debug.log("Autocompleter: search: " + str);
      _currentSearchStr = str;

      var service: HTTPService = new HTTPService;
      service.url = PrivateVars.lastfm.SUGGESTER_URL;
      service.method = "GET";
      var obj: Object = new Object;
      obj["q"] = str;
      obj["rows"] = 15;
      service.request = obj;

      service.addEventListener(ResultEvent.RESULT, onHttpServiceResult);
      service.addEventListener(FaultEvent.FAULT, onHttpServiceFault);
      service.send();
    }

    private function onHttpServiceFault (event: FaultEvent): void
    {
      Debug.log("Autocompleter: onHttpServiceFault: code:" + event.fault.faultCode);
      Debug.log("Autocompleter: onHttpServiceFault: string:" + event.fault.faultString);
      Debug.log("Autocompleter: onHttpServiceFault: details: " + event.fault.faultDetail);
    }

    private function onHttpServiceResult (event: ResultEvent): void
    {
      if (null == event.result)
      {
        Debug.log("Autocompleter: onSearchResult: null result");
        return;
      }

      Debug.log("Autocompleter: onSearchResult: " + event.result);
      var decodedJson: Object = vk.api.serialization.json.JSON.decode(event.result as String);
      if (null == decodedJson || null == decodedJson.response || null == decodedJson.response.docs)
      {
        Debug.log("Autocompleter: onSearchResult: null json result");
        return;
      }

      var artistFilter: Function = function (element:*, index:int, arr:Array): Boolean
      {
        var res:Boolean = true;
        res &&= (-1 != this.types.indexOf(element.restype));

        // TODO: reach:100 and length:50 - are current restrictions.
        res &&= (100 <= element.reach);
        if (element.artist)
        {
          res &&= (50 > element.artist.length);
      }

        return res;
      }

      var newevent: lastfm.events.AutocompleterEvent = new AutocompleterEvent(AutocompleterEvent.SEARCH_RESULT);
      var arr:Array = decodedJson.response.docs.filter(artistFilter, this);
      newevent.result.suggestions = new ArrayList(arr.sortOn("reach", Array.NUMERIC | Array.DESCENDING));
      dispatchEvent(newevent);
    }
  }

}